package com.binance.binancedemo.adapter

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.view.ViewGroup

import com.binance.binancedemo.App
import com.binance.binancedemo.fragment.QuotationFragment

class CommonPagerAdapter(fm: FragmentManager, private val mFragments: MutableList<Fragment>) : FragmentPagerAdapter(fm) {

    init {
        fm.beginTransaction().commitAllowingStateLoss()
    }

    override fun getItem(position: Int): Fragment {
        return mFragments[position]
    }

    override fun getPageTitle(position: Int): CharSequence {
        val fragment = mFragments[position]
        if (fragment is QuotationFragment) {
            return fragment.arguments.getString(QuotationFragment.TYPE)
        }
        return ""
    }

    override fun getItemId(position: Int): Long {
        return (mFragments.size * 100 + position).toLong()
    }

    override fun getCount(): Int {
        return mFragments.size
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any? {
        val fragObject = super.instantiateItem(container, position)
        if (fragObject != null && fragObject is Fragment) {
            if (mFragments.size > position) {
                val initFragment = mFragments[position]
                if (initFragment != null && initFragment.arguments != null) {
                    fragObject.arguments = initFragment.arguments
                }
                mFragments[position] = fragObject
            }
        }
        return fragObject
    }

}
